package com.dinadi.yidi.ui.fragment;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.SortAdapter;
import com.dinadi.yidi.base.BaseFragment;
import com.dinadi.yidi.bean.MessageBean;
import com.dinadi.yidi.bean.PinyinComparator;
import com.dinadi.yidi.bean.TotalDesignerRequest;
import com.dinadi.yidi.bean.TotalDesignerRequestEntity;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.view.ClearEditText;
import com.dinadi.yidi.ui.view.NoNetwork;
import com.dinadi.yidi.ui.view.SideBar;
import com.dinadi.yidi.utils.CharacterParser;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.NetworkUtils;
import com.dinadi.yidi.utils.SharePreferencesHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * author: JiaYu.He
 * Date: 2017/3/25
 * Time: 13:55
 */

public class AZFragmnet extends BaseFragment {
    private View view;
    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;
    private ClearEditText mClearEditText;
    private List<TotalDesignerRequestEntity> dataList = new ArrayList<>();
    private String token, userId;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    /*判断网络*/
    private NoNetwork noNetwork;

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected View getLayout() {
        view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_a_z, null);
        return view;
    }

    @Override
    protected void initView() {
        changePager(2);
        noNetwork = (NoNetwork) view.findViewById(R.id.no_network);
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) view.findViewById(R.id.sidrbar);
        dialog = (TextView) view.findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });

        sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
            }
        });


        //  String[] str = SharePreferencesHelper.getInstance(getActivity()).getSharedPreference("data");


        mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);

        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    protected void initListener() {
        noNetwork.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isNetwork()) {
                    getDate();
                } else {
                    toast("请检查您的网络！");
                }
            }
        });
    }

    @Override
    protected void clickEvent(View v) {

    }

    @Override
    protected void initData() {
        // toast("333");
        userId = SharePreferencesHelper.getInstance(getActivity()).getString("userId");
        token = SharePreferencesHelper.getInstance(getActivity()).getString("token");
        if (isNetwork()) {
            showNoNetwork(false, false);
            getDate();
        } else {
            showNoNetwork(true, true);
        }


    }

    private void getDate() {
        String pageNum = "1";
        String pageSize = "200";
        MessageBean bean = new MessageBean();
        bean.setToken(token);
        bean.setUserId(userId);
        bean.setPageNum(pageNum);
        bean.setPageSize(pageSize);
        showLoadingDialog(getResources().getString(R.string.dialog_text));
        CommonInterface messageInterface = new CommonInterface(getActivity(), httpListener);
        messageInterface.getInterface("13001", JSON.toJSONString(bean));
    }

    private boolean isNetwork() {
        return NetworkUtils.isNetworkAvailable(getActivity());
    }

    private void showNoNetwork(boolean isShow, boolean isShowSetting) {
        if (isShow) {
            noNetwork.setVisibility(View.VISIBLE);
            noNetwork.setNetworkSettings(isShowSetting);
        } else {
            noNetwork.setVisibility(View.GONE);
        }
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<TotalDesignerRequestEntity> filledData(String[] date) {
        List<TotalDesignerRequestEntity> mSortList = new ArrayList<TotalDesignerRequestEntity>();
        for (int i = 0; i < date.length; i++) {
            TotalDesignerRequestEntity sortModel = new TotalDesignerRequestEntity();
            sortModel.setNickName(date[i]);
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<TotalDesignerRequestEntity> filterDateList = new ArrayList<TotalDesignerRequestEntity>();

        if (TextUtils.isEmpty(filterStr)) {
            if (filterDateList.size() != 0) {
                filterDateList = dataList;
                // 根据a-z进行排序
                Collections.sort(filterDateList, pinyinComparator);
                adapter.updateListView(filterDateList);
            } else {
            }

        } else {
            filterDateList.clear();
            for (TotalDesignerRequestEntity sortModel : dataList) {
                String name = sortModel.getNickName();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
            // 根据a-z进行排序
            Collections.sort(filterDateList, pinyinComparator);
            adapter.updateListView(filterDateList);
        }

    }

    HttpListener httpListener = new HttpListener() {

        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            showNoNetwork(false, false);
            String errCode = JsonUtil.getFieldValue(response.toString(), "errCode");
            String errMsg = JsonUtil.getFieldValue(response.toString(), "errMsg");
            if (errCode.equals("0000")) {
                closeLoadingDialog();
                TotalDesignerRequest bean = JsonUtil.parseJsonToBean(response.toString(), TotalDesignerRequest.class);
                dataList = bean.getDesignerList();

                String[] str;
                str = new String[dataList.size()];
                for (int i = 0; i < str.length; i++) {
                    String name = dataList.get(i).getNickName();
                    String dID = dataList.get(i).getUserId();
                    //   str = new String[i];
                    str[i] = name + dID;
                }

                dataList = filledData(str);
                // 根据a-z进行排序源数据
                Collections.sort(dataList, pinyinComparator);
                adapter = new SortAdapter(getActivity(), dataList);
                sortListView.setAdapter(adapter);
                //     SharePreferencesHelper.getInstance(getActivity()).setSharedPreference("data", str);

            } else {
                toast(errMsg);
            }


        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            closeLoadingDialog();
            showNoNetwork(false, false);
            toast("加载失败");
        }
    };

}
